<template>
  <div>
    <el-row class="nav">
      <span class="font-weight">工单触发器</span>
    </el-row>
    <el-divider></el-divider>
    <el-form :inline="true"
             class="coverage-style-searchForm">
      <el-form-item>
        <div class="demo-input-suffix">
          <el-input prefix-icon="el-icon-search"
                    label="搜索："
                    clearable
                    placeholder="请输入触发器名称"
                    class="key-word-search"
                    v-model='triggerKeyInfo'>
          </el-input>
        </div>
      </el-form-item>
      <el-form-item>
        <button @click="getTriggerListInfo"
                type="button"
                class="el-button el-button--primary el-button--medium h30Btn ">查询</button>
      </el-form-item>
      <el-form-item class="fr">
        <button type="button"
                @click="createTrigger"
                class="el-button el-button--primary el-button--medium h30Btn ">新建触发器</button>
      </el-form-item>
    </el-form>
    <el-row>
      <el-table stripe
                border
                :header-cell-style="{background:'#F2F3F8'}"
                :data="tableData"
                @select="pinSelect"
                ref="multipleTable"
                tooltip-effect="dark"
                style="width: 100%"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection"
                         align="center"
                         min-width="10%">
        </el-table-column>
        <el-table-column label="触发器名称"
                         align="center">
          <template slot-scope="scope">{{ scope.row.triggerName }}</template>
        </el-table-column>
        <el-table-column prop="name"
                         label="状态"
                         align="center">
          <template slot-scope="scope">{{ scope.row.status == '0' ? '启用':'停用' }}</template>
        </el-table-column>
        <el-table-column prop="address"
                         label="创建时间"
                         align="center"
                         show-overflow-tooltip>
          <template slot-scope="scope">{{timestampToTime(scope.row.createTime)}}</template>

        </el-table-column>
        <el-table-column prop="address"
                         label="创建人"
                         align="center"
                         show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.createUserName }}</template>
        </el-table-column>
        <el-table-column prop="address"
                         label="描述"
                         align="center"
                         show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.triggerDescribe }}</template>
        </el-table-column>
        <el-table-column prop="address"
                         label="操作"
                         align="center"
                         width='300px'
                         show-overflow-tooltip>
          <template slot-scope="scope">
            <el-button type="text"
                       size="mini"
                       class="run-and-stop"
                       @click="handleChange(scope.$index, scope.row)">
              <span v-if="scope.row.status == '1'">
                <img src="../../../assets/images/start.png"
                     alt />启用
              </span>
              <span v-else>
                <img src="../../../assets/images/stop.png"
                     alt />停用
              </span>
            </el-button>
            <el-button icon="el-icon-delete"
                       type="text"
                       size="mini"
                       @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
            <el-button icon="el-icon-edit"
                       type="text"
                       size="mini"
                       @click="handleEdit(scope.$index, scope.row)">编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row class="paging-foot page-foot-spacing"
            :gutter="20">
      <el-col :span="14"
              style="white-space:nowrap;display:flex;align-items:center">
        <span class="color-select">批量操作</span>
        <span class="select-number">（已选中{{selectAllIdLength}}条）</span>
        <el-button type="button"
                   @click='handleDelete'
                   class="el-button el-button--primary el-button--medium h30Btn  btn30-default">删除</el-button>
        <!-- <el-button type="button"
                    @click = "handleChange"
                    class="el-button el-button--primary el-button--medium h30Btn  btn30-default">停用</el-button> -->
      </el-col>
      <el-col :span="10">
        <div class="fr"
             v-if="totalDataLength>0">
          <el-pagination background
                         class="el-pagination-style"
                         @size-change="handleSizeChange"
                         @current-change="handleCurrentChange"
                         :current-page="page"
                         :page-sizes="[10, 20, 50, 100]"
                         :page-size="pageSize"
                         layout="total, sizes, prev, pager, next, jumper"
                         :total="totalDataLength"></el-pagination>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { batchDelete, batchUpdateStatus, getTriggerList } from '@/api/WorkOrderTriggerInfoController.js'
import common from '@/common/common.js'
export default {
  // inject: ['reload'], // 引入页面同步刷新的依赖
  data () {
    return {
      // status 0为启用,1为停用
      lists: [],
      changeLists: [],
      origin: -1,
      pin: false,
      triggerKeyInfo: '',
      status: '0',
      triggerIdList: [],
      tableData: [],
      multipleSelection: [],
      selectAllIdLength: 0,
      totalDataLength: 0,
      page: 1,
      pageSize: 10
    }
  },
  mounted () {
    this.getTriggerListInfo()
    window.addEventListener('keydown', code => { // 这个是获取键盘按住事件
      // console.log(code) // 这个是你按住键盘打印出键盘信息，在浏览器中自行查看
      if (code.keyCode === 16 && code.shiftKey) { // 判断是否按住shift键，是就把pin赋值为true
        this.pin = true
      }
    })
    window.addEventListener('keyup', code => { // 这个是获取键盘松开事件
      if (code.keyCode === 16) { // 判断是否松开shift键，是就把pin赋值为false
        this.pin = false
        if (this.lists.length > 2) {
          this.triggerIdList = this.lists
        } else {
          this.triggerIdList = this.changeLists
        }
        this.selectAllIdLength = this.triggerIdList.length
      }
    })
  },
  destroyed () {
    window.removeEventListener('keydown', code => {
      if (code.keyCode === 16 && code.shiftKey) {
        this.pin = true
      }
    }, false)
    window.removeEventListener('keyup', code => {
      if (code.keyCode === 16) {
        this.pin = false
      }
    }, false)
  },
  methods: {
    // 这里是select事件开始
    pinSelect (item, row) {
      const data = this.tableData // 获取所有数据
      const origin = this.origin // 起点数 从-1开始
      const endIdx = row.index // 终点数
      if (this.pin && item.includes(data[origin])) { // 判断按住
        // this.$refs.multipleTable.selectClear()
        const sum = Math.abs(origin - endIdx) + 1// 这里记录终点
        const min = Math.min(origin, endIdx)// 这里记录起点
        let i = 0

        while (i < sum) {
          const index = min + i
          this.$refs.multipleTable.toggleRowSelection(data[index], true) // 通过ref打点调用toggleRowSelection方法，第二个必须为true
          i++
        }
        this.lists = this.triggerIdList
      } else {
        this.origin = row.index // 没按住记录起点或没选起点
        this.lists = []
      }
    },
    // 时间戳的转换
    timestampToTime (timestamp) {
      return common.timestampToTime(timestamp)
    },
    // 搜索数据列表
    getTriggerListInfo () {
      let params = {
        createUserId: this.$store.state.userId + '',
        page: this.page,
        pageSize: this.pageSize,
        triggerName: this.triggerKeyInfo // 触发器名称
      }
      getTriggerList(params).then(res => {
        let data = res.data
        if (data.retCode === 200) {
          this.tableData = data.data
          this.totalDataLength = data.count
          this.origin = -1
          this.tableData.forEach((item, index) => {// 遍历索引,赋值给data数据
            item.index = index
          })
        } else {
          this.$message({
            type: 'error',
            message: data.msg
          })
        }
      })
    },
    // 新建触发器
    createTrigger () {
      this.$store.commit('orderTitleFun', '新建触发器')// 主标题
      this.$router.push('/createWorkTrigger')
      this.$store.commit('tiggerIdFun', '')
    },
    // 启用停用
    handleChange (index, row) {
      if (row.status == "0") {
        this.status = '1'
      } else {
        this.status = '0'
      }
      this.triggerIdList.push(row.id)
      let params = {
        ids: this.triggerIdList,
        updateUserId: this.$store.state.userId + '',
        status: this.status
      }
      batchUpdateStatus(params).then(res => {
        let data = res.data
        if (data.retCode === 200) {
          this.$message({
            message: data.msg,
            type: 'success'
          })
          row.status = row.status == '1' ? '0' : '1'
          this.triggerIdList = []
        } else {
          this.$message({
            message: data.msg,
            type: 'error'
          })
        }
      })
    },
    // 删除
    handleDelete (index, row) {
      if (!(this.selectAllIdLength > 0 || (row && row.id))) {
        this.$message({
          type: 'error',
          message: '请选择删除项'
        })
        return
      }
      this.$confirm('确定要删除吗？', '确定删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        center: true,
        customClass: 'messageBox-prompt-delete'
      }).then(() => {
        if (row) {
          this.triggerIdList.push(row.id)
        }
        let params = {
          ids: this.triggerIdList,
          updateUserId: this.$store.state.userId + ''
        }
        batchDelete(params).then(res => {
          let data = res.data
          if (data.retCode === 200) {
            this.$message({
              message: data.msg,
              type: 'success'
            })
            this.triggerIdList = []
            this.getTriggerListInfo()
            // this.reload()
          } else {
            this.$message({
              message: data.msg,
              type: 'error'
            })
          }
        })
      }).catch(() => { })
    },
    // 编辑
    handleEdit (index, row) {
      this.$store.commit('tiggerIdFun', row.id)
      this.$store.commit('orderTitleFun', '编辑触发器')// 主标题
      this.$router.push('/createWorkTrigger')
    },
    handleSizeChange (pageSize) {
      this.pageSize = pageSize
      this.page = 1
      this.getTriggerListInfo()
    },
    handleCurrentChange (page) {
      this.page = page
      this.getTriggerListInfo()
    },
    // 选择相对应编号的数据
    handleSelectionChange (val) {
      this.selectAllIdLength = val.length
      this.triggerIdList = []
      val.map((value, key, index) => {
        this.triggerIdList.push(value.id)
      })
      this.changeLists = this.triggerIdList
    },
    toggleSelection (rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    }
  }
}
</script>

<style scoped>
/* .run-and-stop span span {
  display: flex;
  align-items: center;
} */
.select-number {
  color: #b50029;
}
</style>
